<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2021-02-18 16:42:24
// +----------------------------------------------------------------------

namespace buwang\service;

use app\common\model\WechatMessageLog;
use app\common\model\WechatMessageTemplate;
use buwang\facade\WechatProgram;
use app\common\model\User;
use Exception;

/**
 * 微信消息
 * Class WechatMessageService
 * @package buwang\service
 */
class WechatMessageService
{
    /**
     * 发送订阅消息
     * 可发送次数与小程序内订阅次数对应
     * @param int $user_id 用户ID
     * @param string $key 微信消息标识
     * @param array $data 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
     * @param string $page 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function sendSubscribeMessage(int $user_id, string $key, array $data, string $page = ''): bool
    {
        $fail_msg = '';//失败原因
        $param = '';//请求参数

        //获取用户信息
        $user = User::where(['id' => $user_id])->find();
        !$user && $fail_msg .= '用户不存在,';
        !$user['miniapp_uid'] && $fail_msg .= '用户小程序openid不存在,';
        $member_miniapp_id = $user['member_miniapp_id'] ?? 0;//租户应用ID
        //获取微信实例
        $wechat = WechatProgram::getWechatObj($member_miniapp_id);
        !$wechat && $fail_msg = '小程序配置有误,';
        //获取消息模板ID
        $template_id = WechatMessageTemplate::where(['member_miniapp_id' => $member_miniapp_id, 'type' => 0, 'key' => $key, 'status' => 1])->value('template_id');
        !$template_id && $fail_msg .= '消息模板不存在或已关闭,';

        if (!$fail_msg) {
            $param = [
                'template_id' => $template_id,       // 所需下发的订阅模板id
                'touser' => $user['miniapp_uid'],   // 接收者（用户）的 openid
                'page' => $page,                    // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                'data' => $data,
            ];
            $res = $wechat->subscribe_message->send($param);
            $res['errcode'] !== 0 && $fail_msg = "订阅消息发送失败【{$res['errcode']}-{$res['errmsg']}】";
        }

        //添加消息发送记录
        WechatMessageLog::create([
            'type' => 0,
            'member_miniapp_id' => $member_miniapp_id,
            'user_id' => $user_id,
            'key' => $key,
            'param' => json_encode($param),
            'status' => empty($fail_msg),
            'fail_msg' => $fail_msg,
        ]);

        return true;
    }
}